package com.estore.view;

import com.estore.model.Product;
import com.estore.service.ProductService;
import java.util.*;
import java.io.*;  // 新增import

public class ConsoleShop {
    private final ProductService productService = new ProductService();
    private final Map<String, Integer> shoppingCart = new HashMap<>();
    private final Scanner scanner = new Scanner(System.in);

    public void start() {
        System.out.println("🛍️ 欢迎来到电子商城！");

        while (true) {
            showMenu();
            try {
                int choice = scanner.nextInt();
                scanner.nextLine(); // 消费掉换行符

                switch (choice) {
                    case 1:
                        browseProducts();
                        break;
                    case 2:
                        addToCart();
                        break;
                    case 3:
                        viewCart();
                        break;
                    case 4:
                        checkout();
                        break;
                    case 5:
                        exitSystem();
                        return;
                    case 99: // 隐藏的管理员功能 - 数据备份
                        backupData();
                        break;
                    default:
                        System.out.println("无效的选项，请重新输入！");
                }
            } catch (InputMismatchException e) {
                System.out.println("请输入有效的数字！");
                scanner.nextLine(); // 清除无效输入
            }
        }
    }

    private void showMenu() {
        System.out.println("\n========== 商城菜单 ==========");
        System.out.println("1. 浏览所有商品");
        System.out.println("2. 添加商品到购物车");
        System.out.println("3. 查看购物车");
        System.out.println("4. 结算订单");
        System.out.println("5. 退出");
        System.out.print("请输入您的选择: ");
    }

    private void browseProducts() {
        System.out.println("\n--- 商品列表 ---");
        List<Product> products = productService.getAllProducts();
        if (products.isEmpty()) {
            System.out.println("商店里还没有商品。");
        } else {
            products.forEach(product -> {
                String status = product.getStock() > 0 ? "有货" : "缺货";
                System.out.println(product + " | 状态: " + status);
            });
        }
    }

    private void addToCart() {
        System.out.print("请输入要添加的商品ID: ");
        String productId = scanner.nextLine();
        Product product = productService.findProductById(productId);

        if (product == null) {
            System.out.println("错误：找不到该商品！");
            return;
        }
        if (product.getStock() <= 0) {
            System.out.println("抱歉，该商品已售罄。");
            return;
        }

        System.out.print("请输入购买数量: ");
        try {
            int quantity = scanner.nextInt();
            scanner.nextLine(); // 消费换行符

            if (quantity <= 0) {
                System.out.println("错误：购买数量必须为正数！");
                return;
            }
            if (quantity > product.getStock()) {
                System.out.println("错误：库存不足！当前库存为 " + product.getStock());
                return;
            }

            // 将商品加入购物车，如果已存在则累加数量
            int currentQuantity = shoppingCart.getOrDefault(productId, 0);
            shoppingCart.put(productId, currentQuantity + quantity);
            System.out.println("✅ 成功将 '" + product.getName() + "' 添加到购物车！");

        } catch (InputMismatchException e) {
            System.out.println("错误：请输入有效的数字！");
            scanner.nextLine();
        }
    }

    private void viewCart() {
        System.out.println("\n--- 我的购物车 ---");
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车是空的，快去逛逛吧！");
            return;
        }

        double total = 0.0;
        int itemCount = 0;

        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            String productId = entry.getKey();
            Integer quantity = entry.getValue();
            Product product = productService.findProductById(productId);
            if (product != null) {
                double subtotal = product.getPrice() * quantity;
                System.out.printf("商品: %-20s | 单价: ¥%-8.2f | 数量: %-3d | 小计: ¥%.2f\n",
                        product.getName(), product.getPrice(), quantity, subtotal);
                total += subtotal;
                itemCount += quantity;
            }
        }
        System.out.println("----------------------------------------");
        System.out.printf("商品总数: %d 件\n", itemCount);
        System.out.printf("订单总计: ¥%.2f\n", total);
    }

    private void checkout() {
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车是空的，无法结算！");
            return;
        }

        System.out.println("\n--- 订单结算 ---");
        viewCart();

        System.out.print("\n确认下单吗？(y/n): ");
        String confirm = scanner.nextLine();

        if ("y".equalsIgnoreCase(confirm)) {
            // 检查库存并扣减
            boolean stockSufficient = true;
            for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
                Product product = productService.findProductById(entry.getKey());
                if (product.getStock() < entry.getValue()) {
                    System.out.println("错误：商品 '" + product.getName() + "' 库存不足！");
                    stockSufficient = false;
                    break;
                }
            }

            if (stockSufficient) {
                // 扣减库存
                for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
                    productService.decreaseProductStock(entry.getKey(), entry.getValue());
                }

                double total = calculateTotal();
                System.out.printf("✅ 订单提交成功！总计: ¥%.2f\n", total);
                shoppingCart.clear();
            }
        } else {
            System.out.println("订单已取消。");
        }
    }

    private double calculateTotal() {
        double total = 0.0;
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            Product product = productService.findProductById(entry.getKey());
            if (product != null) {
                total += product.getPrice() * entry.getValue();
            }
        }
        return total;
    }

    /**
     * 退出系统，保存数据
     */
    private void exitSystem() {
        System.out.println("正在保存数据...");
        productService.saveData();
        System.out.println("感谢使用，再见！");
    }

    /**
     * 数据备份功能（任务三）
     */
    private void backupData() {
        String sourceFile = "products.dat";
        String backupFile = "products.dat.bak";

        File source = new File(sourceFile);
        if (!source.exists()) {
            System.out.println("❌ 备份失败: 源数据文件不存在 - " + sourceFile);
            return;
        }

        try (FileInputStream fis = new FileInputStream(sourceFile);
             FileOutputStream fos = new FileOutputStream(backupFile)) {

            byte[] buffer = new byte[1024]; // 1KB缓冲区
            int bytesRead;
            long totalBytes = 0;

            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
                totalBytes += bytesRead;
            }

            System.out.printf("✅ 数据备份成功！备份文件: %s (大小: %.2f KB)%n",
                    backupFile, totalBytes / 1024.0);

        } catch (FileNotFoundException e) {
            System.out.println("❌ 备份失败: 数据文件不存在");
        } catch (IOException e) {
            System.out.println("❌ 备份失败: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        new ConsoleShop().start();
    }
}